package com.alipay.api.test.fsf;
 
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;

import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
 
public class ZipFileHandler {
	
    private final static int buffer = 1024;
    
    /**
     * 第一步： 把 支付宝生成的账单 下载到本地目录
     * 
     * @param path
     *            支付宝资源url
     * @param filePath
     *            生成的zip 包目录
     * @throws MalformedURLException
     */
    public static void downloadNet(String path, String filePath)
            throws MalformedURLException {
        // 下载网络文件
        int bytesum = 0;
        int byteread = 0;

        URL url = new URL(path);
        URLConnection conn = null;
        InputStream inStream = null;
        FileOutputStream fs = null;
        try {
            conn = url.openConnection();
             inStream = conn.getInputStream();
            fs = new FileOutputStream(filePath);

            byte[] by = new byte[buffer];
            while ((byteread = inStream.read(by)) != -1) {
                bytesum += byteread;
                fs.write(by, 0, byteread);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        	if(fs!=null){
        		try {
					fs.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
        	}
        	if(inStream!=null){
        		try {
					inStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
        	}
        }
    }
    
    
 
    /**
     * 创建目录
     * @author fangshufeng   2018年2月9日
     */
    private void createDirectory(String directory, String subDirectory) {
        String dir[];
        File fl = new File(directory);
        try {
            if (subDirectory == "" && fl.exists() != true) {
                fl.mkdir();
            } else if (subDirectory != "") {
                dir = subDirectory.replace('\\', '/').split("/");
                for (int i = 0; i < dir.length; i++) {
                    File subFile = new File(directory + File.separator + dir[i]);
                    if (subFile.exists() == false) {
                        subFile.mkdir();
                    }
                    directory += File.separator + dir[i];
                }
            }
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }
 
    /**
     * 解压文件
     * @author fangshufeng   2018年2月9日
     */
    @SuppressWarnings("unchecked")
    public boolean  unZip(String zipFilePath, String outputDirectory) {
        boolean flag = false;
        try {
            ZipFile zipFile = new ZipFile(zipFilePath,"GBK");
            Enumeration e = zipFile.getEntries();
            ZipEntry zipEntry = null;
            createDirectory(outputDirectory, "");
            while (e.hasMoreElements()) {
                zipEntry = (ZipEntry) e.nextElement();
                System.out.println("unzip " + zipEntry.getName());
                if (zipEntry.isDirectory()) {
                    String name = zipEntry.getName().trim();
                    name = name.substring(0, name.length() - 1);
                    File f = new File(outputDirectory + File.separator + name);
                    if (!f.exists()) {
                        f.mkdir();
                    }
 
                } else {
                    String fileName = zipEntry.getName();
                    fileName = fileName.replace('\\', '/');
                    if (fileName.indexOf("/") != -1) {
                        createDirectory(outputDirectory, fileName.substring(0,
                                fileName.lastIndexOf("/")));
                        fileName = fileName
                                .substring(fileName.lastIndexOf("/") + 1);
                    }
                    File f = new File(outputDirectory + File.separator
                            + zipEntry.getName());
                    f.createNewFile();
                    InputStream in = zipFile.getInputStream(zipEntry);
                    FileOutputStream out = new FileOutputStream(f);
                    byte[] by = new byte[buffer];
                    int c;
                    while ((c = in.read(by)) != -1) {
                        out.write(by, 0, c);
                    }
                    in.close();
                    out.close();
                }
            }
            flag = true;
            System.out.println("unzip finished");
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }       
        return flag;
    }
 
    
    /**
     * 压缩文件
     * @author fangshufeng   2018年2月9日
     */
    public boolean zip(String srcDirName, String zipFilePath) {
        boolean flag = false;
        try {
            File srcdir = new File(srcDirName);
            if (!srcdir.exists())
                throw new RuntimeException(srcDirName + " is not exist!");
 
            Project prj = new Project();
            Zip zip_ = new Zip();
            zip_.setProject(prj);
            zip_.setDestFile(new File(zipFilePath));
 
            FileSet fileSet = new FileSet();
            fileSet.setProject(prj);
            fileSet.setDir(srcdir);
            zip_.addFileset(fileSet);
 
            zip_.execute();
            flag = true;
            System.out.println("zip finished");
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        return flag;
    }
 
    public static void main(String[] args) throws Exception {
    	//测试下载SDK
    	downloadNet("https://openhome.alipay.com/doc/sdkDownload.resource?sdkType=JAVA", "f://2018.zip");
    	
      /*  ZipFileHandler zh = new ZipFileHandler();
        zh.unZip("d:\\test.zip", "d:\\test1");
        zh.zip("d:\\test1", "d:\\test1.zip");*/
    	System.out.println("ok");
    }
 
}